package chomsky;

import com.sun.org.apache.xml.internal.serializer.utils.Messages;
import javax.mail.Message;

;

import com.sun.mail.imap.IMAPMessage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Folder;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;

/**
 *
 * @author Anarcaster
 */
public class Reader {

    private static final String MAILS_STORE_PATH = "./output/mails_read";
    
    public void getMails(Properties connectionParams) throws IOException{

        try {
            
            //Establece sesión
            Session session = Session.getInstance(connectionParams);
            session.setDebug(true);
            Store store = session.getStore("imaps");
            store.connect(connectionParams.getProperty("mail.imap.host"),
                          connectionParams.getProperty("mail.imap.username"),
                          connectionParams.getProperty("mail.imap.password"));
           
            //Accede a carpeta "Comunidad"
            Folder folder = store.getFolder("Comunidad");
            folder.open(Folder.READ_ONLY);
            Message[] messages = folder.getMessages();
                   
            //Para cada mail, vuelca el contenido en un fichero diferente
            for (int j = 0; j < 1000; j++) {

                //Creo fichero con extension el número de orden
                File file = new File(Reader.MAILS_STORE_PATH + "." + j);
                FileOutputStream fos = new FileOutputStream(file);

                //Obtengo el contenido del mail
                InputStream is = messages[j].getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is);

                //Vuelco
                int len;
                byte buf[] = new byte[1024];
                while((len=is.read(buf))>0){
                    fos.write(buf,0,len);
                }

                fos.close();
                is.close();
                
                System.out.println("\nFile is created");
            }
        } catch (MessagingException ex) {
            Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null, ex);
        }

      }
}

